package com.youdianstar.app.ui.op

import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.PopupWindow
import com.gyf.immersionbar.ImmersionBar
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.MathUtil
import com.youdianstar.app.BR
import com.youdianstar.app.R
import com.youdianstar.app.databinding.OpMerchantCenterBinding
import com.youdianstar.app.entity.MerchantOP
import com.youdianstar.app.entity.OpMerchantHome
import com.youdianstar.app.util.AcPopupUtil
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.util.ScreenUtil
import com.youdianstar.app.common.auko.startActivity
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: MerchantCenterActivity
 * Author: 82149 Create: 2023/8/1 15:11
 * Changes (from 2023/8/1)
 * --------------------------------------------------
 * description: 商户中心
 * ---------------------------------------------------
 *
 */
class MerchantCenterActivity : BaseActivity<OpMerchantCenterBinding, OPMerchantViewModel>() {

    override fun layoutId(): Int = R.layout.op_merchant_center

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): OPMerchantViewModel {
        val model: OPMerchantViewModel by viewModel()
        return model
    }

    private var popupTag = false
    private var opWindow : PopupWindow? = null
    private var merchantOPList: MutableList<MerchantOP> = mutableListOf()
    private var windowWidth = 0
    private var selectId = 0
    private val mHandler = Handler(Looper.myLooper()!!)

    override fun initData() {
        super.initData()
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .statusBarColor(R.color.white)
            .titleBarMarginTop(mBinding.topActionBar)
            .init()

        mBinding.swHome.setOnRefreshListener {
            loadHomeData(false)
        }
        windowWidth = (ScreenUtil.getScreenSize(this).x * 0.82).toInt()

        // TODO: 测试阶段 - 商户中心功能已开启
        // 所有用户都可以访问商户中心进行测试
        // 正式发布时需要根据用户权限进行访问控制
        
        // 恢复正常的API调用
        popupTag = false
        mViewModel.getShopConfigList(true)
    }

    override fun onResume() {
        super.onResume()
        if (DataAppManager.instance.shopEdtTag>0){
            mViewModel.getShopConfigList(true)
        }
    }

    override fun initClickEvent() {
        mBinding.ivBack.setThrottleListener {
            finish()
        }

        mBinding.llSwitchMerchant.setThrottleListener {
            if (merchantOPList.isEmpty()){
                popupTag = true
                mViewModel.getShopConfigList(true)
            }else{
                showOpSelectWindow()
            }
        }

        mBinding.btnWithdrawal.setThrottleListener {
            mViewModel.merchantDataField.get()?.let { data ->
                startActivity<WithdrawalActivity>(Extra.IT_ID to selectId,Extra.IT_MONEY to data.pendingAmount)
            }
        }

        mBinding.tvWitchRecord.setThrottleListener {
            startActivity<WithdrawalRcActivity>(Extra.IT_ID to selectId)
        }

        mBinding.clOrder.setThrottleListener {
            startActivity<OPOrderActivity>(Extra.IT_ID to selectId)
        }

        mBinding.clTransRecord.setThrottleListener {
            startActivity<OPTransactionActivity>(Extra.IT_ID to selectId)
        }

        mBinding.clDevice.setThrottleListener {
            startActivity<DeviceListActivity>(Extra.IT_ID to selectId)
        }

        mBinding.clSetting.setThrottleListener {
            //编辑商户信息
            startActivity<ShopInfoActivity>(Extra.IT_ID to selectId)
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.shopConfigListLiveData.observe(this, object :BaseApiResultObserver<List<MerchantOP>>(){
            override fun onDataResult(data: List<MerchantOP>?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let { list ->
                    merchantOPList.clear()
                    if (list.isNotEmpty()){
                        merchantOPList.add(MerchantOP(id = 0, branchName = getString(R.string.shop_totalMerchant)))
                        merchantOPList.addAll(list)
                    }
                    if (popupTag){
                        showOpSelectWindow()
                    }else{
                        //默认选择第一个(如果有编辑-选中编辑对应id)
                        if (merchantOPList.isNotEmpty()){
                            merchantOPList.forEach { op ->
                                if (op.id == DataAppManager.instance.shopEdtTag){
                                    op.isSelect = true
                                    setSelectMerchant(op)
                                }
                            }
                        }
                    }
                    DataAppManager.instance.shopEdtTag = 0
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
                if (code == 21334){
                    DataAppManager.instance.userUpdateTag = true
                    mHandler.postDelayed({
                        finish()
                    },1000L)
                }
            }
        })

        mViewModel.centerStatisticsLiveData.observe(this, object : BaseApiResultObserver<OpMerchantHome>() {
                override fun onDataResult(data: OpMerchantHome?) {
                    super.onDataResult(data)
                    dismissDialog()
                    data?.let {
                        updateCenterLayout(it)
                        mBinding.swHome.isRefreshing = false
                    }
                }

                override fun onNetError(code: Int, e: String?) {
                    super.onNetError(code, e)
                    mBinding.swHome.isRefreshing = false
                    dismissDialog()
                    toastShow(e)
                    if (code == 21334)
                        DataAppManager.instance.userUpdateTag = true
                }
            })
    }

    private fun updateCenterLayout(data: OpMerchantHome) {
        mViewModel.merchantDataField.set(data)
        val symbolStr = DataAppManager.instance.symbolTx()
        mBinding.tvCountValue1.text = symbolStr + MathUtil.round(data.profitToday)
        mBinding.tvCountValue2.text = data.todayTotalOrder.toString()
        mBinding.tvBalance.text = symbolStr + MathUtil.round(data.pendingAmount)

        mBinding.tvAllProfits.text = symbolStr + MathUtil.round(data.profitTotal)
        mBinding.tvTotalOrder.text = data.totalOrder.toString()
        mBinding.tvPayouts.text = symbolStr + MathUtil.round(data.settledAmount)
    }

    /**
     * 设置选中 网点id
     * @param item 商家选择
     */
    private fun setSelectMerchant(item:MerchantOP){
        selectId = item.id
        mBinding.tvNameSelected.text = item.merchantName()
        mBinding.tvWitchRecord.visibility = if (selectId == 0) View.INVISIBLE else View.VISIBLE
        mBinding.btnWithdrawal.visibility = if (selectId == 0) View.INVISIBLE else View.VISIBLE
        mBinding.clSetting.visibility = if (selectId == 0) View.GONE else View.VISIBLE
        loadHomeData(true)
    }

    private fun loadHomeData(isShow: Boolean = false) {
        // 恢复正常的API调用
        mViewModel.getMerchantCenterCount(if (selectId == 0) null else selectId,isShow)
    }

    /**
     * 操作商家切换
     *
     * -PopupWindow形式
     */
    private fun showOpSelectWindow() {
        opWindow?.dismiss()
        opWindow = null
        opWindow = AcPopupUtil.instance.showOPPopupWindow(this, mBinding.llSwitchMerchant, widthP = windowWidth, merchantOPList) { index ->
            setSelectMerchant(merchantOPList[index])
            loadHomeData(true)
        }
    }

}